﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Jzy.Model;
using Jzy.DAL.Mail;

using System.Data;
using Jzy.Model.Mail;
using System.Web;
using System.Transactions;

using Frame.Lib.Core.Base;
using Frame.Lib.Core.Dept;
using Frame.Lib.Core.User;
using Frame.Lib.Utilities;
using Frame.Lib.Core.Attach;
using Frame.Lib.Core.Log;
using Frame.Lib.Enums;
using Jzy.DAL;

namespace Jzy.BLL.Mail
{
    public class MailBO:CommonOperate<MailInfo>
    {
        private MailDAL _mail;
        protected override BaseDAL DAL
        {
            get
            {
                return _mail;
            }
        }
        private int _userID;

        public MailBO(int userID)
            : base("Mail")
        {
            this._userID = userID;
            _mail = new MailDAL(userID);
            _mail.dbOper = base.dbOper;
        }

        public DataTable GetList(int folderID, MailStatus status)
        {
            DataTable dt = _mail.GetList(folderID, status);
            dt.Columns.Add("MailFlag");
            foreach (DataRow dr in dt.Rows)
            {
                int bytStatus = (int)dr["Status"];
                switch (bytStatus)
                {
                    case 0:
                        dr["MailFlag"] = "~/common/images/Mail/UnRead.gif";
                        break;
                    case 1:
                        dr["MailFlag"] = "~/common/images/Mail/Read.gif";
                        break;
                    case 3:
                        dr["MailFlag"] = "~/common/images/Mail/Re.gif";
                        break;
                    case 5:
                        dr["MailFlag"] = "~/common/images/Mail/Fw.gif";
                        break;
                    case 7:
                        dr["MailFlag"] = "~/common/images/Mail/ReFw.gif";
                        break;
                }
            }
            return dt;
        }

        public void Move(List<string> lstMailUserIDs, object destFolder)
        {
            _mail.Move(lstMailUserIDs, destFolder);
        }

        public void Move(string mailUserIDs, object destFolder)
        {
            List<string> lstMailUserIDs = new List<string>();
            lstMailUserIDs.Add(mailUserIDs);
            _mail.Move(lstMailUserIDs, destFolder);
        }

        public void DeleteBoxMail(List<string> lstMailUserIDs)
        {
            _mail.DeleteBoxMail(lstMailUserIDs);
        }

        public void DeleteBoxMail(string mailUserID)
        {
            _mail.DeleteBoxMail(mailUserID);
        }

        #region 在邮件管理时实现
        /// <summary>
        /// 真正的删除邮件,注意要删除相关附件
        /// </summary>
        /// <param name="ids"></param>
        public override void Delete(IEnumerable<int> ids)
        {
            foreach (int id in ids)
            {
                this.Delete(id);
            }
        }

        public override void Delete(IEnumerable<string> ids)
        {
            foreach (string id in ids)
            {
                this.Delete(id);
            }
        }

        public override void Delete(int id)
        {
            AttachBO attach = new AttachBO(OTableName.Mail);

            attach.DeleteByBindID(id);

            base.Delete(id);
        }
        #endregion

        public bool Send(MailInfo info, HttpFileCollection files, WriteMailMode mode)
        {
            DeptBO dept = new DeptBO();

            List<int> lstRecieveUserIDs = new List<int>();
            List<int> lstRecieveDeptIDs = new List<int>();
            DeptBO.SplitDeptUser(info.RecieveIDs.ToString(), lstRecieveDeptIDs, lstRecieveUserIDs);

            UserBO user = new UserBO();
            
            List<int> lstRecieveIDs = ConvertUtil.MergeList(lstRecieveUserIDs, dept.GetUserIDs(lstRecieveDeptIDs));

            List<int> lstCopyToUserIDs = new List<int>();
            List<int> lstCopyToDeptIDs = new List<int>();
            DeptBO.SplitDeptUser(info.CopyToIDs, lstCopyToDeptIDs, lstCopyToUserIDs);

            lstRecieveIDs = ConvertUtil.MergeList(lstRecieveIDs, lstCopyToUserIDs);
            lstRecieveIDs = ConvertUtil.MergeList(lstRecieveIDs, dept.GetUserIDs(lstRecieveDeptIDs));//合并所有的UserID

            bool flag = true;

            //using (TransactionScope scope = new TransactionScope())
            //{
            try
            {
                base.dbOper.BeginTrans();
                int mailID = 0;//先取回原来邮件的ＩＤ，然后再清空便于插入新记录
                if (mode == WriteMailMode.Reply || mode == WriteMailMode.Forword)
                {
                    mailID = info.ID;
                    info.ID = 0;
                }


                //保存邮件主体
                base.Save(info);

                //保存自己的已发邮件和接收人的邮件
                _mail.Send(info.ID, lstRecieveIDs);

                //保存附件
                if (files != null && files.Count > 0)
                {
                    AttachBO attach = new AttachBO(OTableName.MailAttach);
                    attach.dbOper = base.dbOper;

                    attach.Save(files, info.ID);
                }

               

                switch (mode)
                {
                    case WriteMailMode.Draft: //如果来源于草稿箱，则更新，其余为增加
                        _mail.DeleteBoxMail((int)MailSysFolder.草稿箱, (int)info.ID);//删除草稿箱里的内容
                        break;
                    case WriteMailMode.Forword:
                        {
                            //byte status = mail.GetStatus(BoxType.Recieve, mailID);
                            //status =(byte)(status | (int)MailStatus.Forword);
                            _mail.SetStatus((int)MailSysFolder.收件箱, mailID, MailStatus.Forword);//保存修改后的状态
                        }
                        break;
                    case WriteMailMode.Reply:
                        {
                            //byte status = mail.GetStatus(BoxType.Recieve, mailID);
                            //status =(byte)(status | (byte)MailStatus.Reply);
                            _mail.SetStatus((int)MailSysFolder.收件箱, mailID, MailStatus.Reply);//保存修改后的状态
                        }
                        break;
                }

                base.dbOper.CommitTrans();
                //scope.Complete();
            }
            catch(Exception ex)
            {
                base.dbOper.RollbackTrans();
                Logger.Exception(ex);

                flag = false;
                //scope.Dispose();
            }
            // }
            return flag;
        }

        public void SetRead(string mailUserID)
        {
            //byte status = mail.GetStatus(strFolderID);
            //status = (byte)(status | (int)MailStatus.HaveRead);
            _mail.SetStatus(mailUserID, MailStatus.HaveRead);
        }

        public bool SaveToDraft(MailInfo info, HttpFileCollection files, string mailUserID)
        {
            bool flag = true;
            
            try
            {
                //保存邮件本身
                base.Save(info);

                //保存附件
                AttachBO attach = new AttachBO(OTableName.MailAttach);
                attach.Save(files, info.ID);

                //放进草稿箱
                if (mailUserID == null)//如果从草稿箱中再保存进草稿中不需要增加记录
                {
                    _mail.SaveToDraft(info.ID);
                }
                   
            }
            catch(Exception ex)
            {
                Logger.Exception(ex);
                flag = false;
                    
            }

           
            return flag;
        }

        public int GetMailID(string mailUserID)
        {
            int mailID = _mail.GetMailID(mailUserID);
            return mailID;
        }


        public void CopyAttach(List<int> lstAttachIDs, int mailID)
        {
            AttachBO attach = new AttachBO(OTableName.MailAttach);
            attach.CopyAttach(lstAttachIDs, mailID);
        }

        public int GetUnreadMailCount()
        {
            int mailCount = _mail.GetUnreadMailCount();
            return mailCount;
        }

        public void Clear(object folderID)
        {
            _mail.Clear(folderID);
        }
    }
}
